import axios from 'axios'

interface LoginCredentials {
  email: string
  password: string
}

interface RegisterCredentials extends LoginCredentials {
  username: string
  role: 'STUDENT' | 'TEACHER'
}

interface UserProfile {
  id: string
  username: string
  email: string
  avatar?: string
  role: 'STUDENT' | 'TEACHER'
}

export const authService = {
  async login(credentials: LoginCredentials) {
    try {
      const response = await axios.post('/api/auth/login', credentials)
      return response.data
    } catch (error) {
      throw new Error('登录失败')
    }
  },

  async register(credentials: RegisterCredentials) {
    try {
      const response = await axios.post('/api/auth/register', credentials)
      return response.data
    } catch (error) {
      throw new Error('注册失败')
    }
  },

  async getCurrentUser(): Promise<UserProfile> {
    try {
      const response = await axios.get('/api/auth/profile')
      return response.data
    } catch (error) {
      throw new Error('获取用户信息失败')
    }
  },

  async updateProfile(profileData: Partial<UserProfile>) {
    try {
      const response = await axios.put('/api/auth/profile', profileData)
      return response.data
    } catch (error) {
      throw new Error('更新用户信息失败')
    }
  },

  async updatePassword(passwordData: { 
    currentPassword: string, 
    newPassword: string 
  }) {
    try {
      await axios.put('/api/auth/password', passwordData)
    } catch (error) {
      throw new Error('修改密码失败')
    }
  },

  async uploadAvatar(file: File) {
    try {
      const formData = new FormData()
      formData.append('avatar', file)
      
      const response = await axios.post('/api/auth/avatar', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      
      return response.data
    } catch (error) {
      throw new Error('上传头像失败')
    }
  },

  logout() {
    return axios.post('/auth/logout');
  },

  resetPassword(email: string) {
    return axios.post('/auth/reset-password', { email });
  }
}; 